import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let chatWin = null;

const createchatWin = () => {
    chatWin = new BrowserWindow({
        title: 'Yangshao chat',
        width: 400,
        height: 430,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: false,
        show:false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        chatWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        chatWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    chatWin.webContents.on('did-finish-load', () => {
        chatWin.webContents.send('set-route', '/chat');
    });

    chatWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return chatWin;
}
function closechatWin() {
    if (chatWin && !chatWin?.isDestroyed()) {
        chatWin?.close();
    }
    chatWin = null;
}

function openchatWin() {
    if (!chatWin || chatWin?.isDestroyed()) {
        chatWin = createchatWin();
    }
}
function showchatWin(){
    chatWin?.show();
}
function hidechatWin() {
    chatWin.hide();
}
// 写一个show和hide切换
function showHidechatWin() {
    chatWin.isVisible() ? chatWin.hide() : chatWin.show();
}
function goHomechatWin() {
    chatWin.loadURL('http://localhost:3456/chat')
}

function minimizechatWin() {
    chatWin.minimize();
}

function focuschatWin() {
    if (!chatWin || chatWin?.isDestroyed()) {
        chatWin = createchatWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (chatWin.isMinimized()) chatWin.restore();
        if (!chatWin.isVisible()) chatWin.show();
        chatWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (chatWin && !chatWin?.isDestroyed()) {
        chatWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closechatWin,
    createchatWin,
    showchatWin,
    focuschatWin,
    hidechatWin,
    minimizechatWin,
    openchatWin,
    sendEuUpdateCanAvailable,
    showHidechatWin,
    goHomechatWin
};